package com.yun.zhong.fu.sharecenter.config;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.ribbon.NacosServer;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

/**
 * @Author RenPu
 * @Date 2020/12/29 11:31
 * @Version 1.0
 * @Description: 通过编码的形式实现nacos权重的策略
 **/
@Slf4j
//@Configuration
public class NacosWeightedRule extends AbstractLoadBalancerRule {


    @Autowired
    private  NacosDiscoveryProperties nacosDiscoveryProperties;

    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {
        //读取配置文件，并初始化NacosWeightedRule
    }

    @Override
    public Server choose(Object key) {

        try {
            BaseLoadBalancer loadBalancer = (BaseLoadBalancer) this.getLoadBalancer();

            //想要请求的微服务的名称
            String name = loadBalancer.getName();

            //实现负载均衡算法 拿到服务相关的API
            NamingService namingService = this.nacosDiscoveryProperties.namingServiceInstance();

            //nacos client自动给予权重策略，为我们选择一个可以提供服务的实例进行调用
            Instance instance = namingService.selectOneHealthyInstance(name);

            log.info("选择的实例是：port = {},instance = {}", instance.getPort(), instance);
            return new NacosServer(instance);

        } catch (NacosException e) {
            return null;
        }

    }
}
